home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 344 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.3 KB  |  66 lines

  1. Path: io.UWinnipeg.ca!wsimpson
  2. From: Bill Simpson <wsimpson@uwinnipeg.ca>
  3. Newsgroups: comp.lang.c
  4. Subject: start array at k, not 0
  5. Date: Thu, 4 Jan 1996 10:02:10 -0600
  6. Organization: University of Winnipeg
  7. Message-ID: <Pine.OSF.3.91.960104095358.22268B-100000@io.UWinnipeg.ca>
  8. NNTP-Posting-Host: io.uwinnipeg.ca
  9. Mime-Version: 1.0
  10. Content-Type: TEXT/PLAIN; charset=US-ASCII
  11.  
  12. I have come up with the following 2 methods that allow one to talk about
  13. an array that starts at element k rather than 0.  E.g. 10 element array
  14. y[k] to y[k+10].  Both seem to work.  Is this illusory?  Is one of the
  15. 2 ways better (or a way I haven't mentioned)?
  16.  
  17. These programs set up y[5] to y[14].
  18.  
  19. Thanks very much for any comments.
  20.  
  21. Bill Simpson
  22.  
  23. /*method 1*/
  24. #include <stdio.h>
  25.  
  26. int main(void)
  27.  {
  28.  int i, x[10];
  29.  int* y;
  30.  int offset=5;  /*ie 1st index at 5, y[5]-y[14] */
  31.  y=x-offset;
  32.  
  33.  printf("offset=%d\n",offset);
  34.  
  35.  for (i=offset;i<10+offset;i++)
  36.         {
  37.         y[i]=i;
  38.         printf("%d\n",y[i]);
  39.         }
  40.  return 0;
  41.  }
  42.  
  43. /*method 2*/
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46.  
  47. int main(void)
  48.  {
  49.  int i;
  50.  int* y;
  51.  int offset=5;  
  52.  int n=10;       
  53.  y=malloc(n*sizeof(int));
  54.  
  55.  printf("offset=%d\n",offset);
  56.  
  57.  for (i=offset;i<n+offset;i++)
  58.         {
  59.         y[i]=i;
  60.         printf("%d\n",y[i]);
  61.         }
  62.  return 0;
  63.  }
  64.  
  65.  
  66.